﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SDATA;
using SDLL;
using DevComponents.DotNetBar.SuperGrid;
using SCBX;
using SGUI;

namespace SABI
{
    public partial class frm0188 : Form
    {
        string sql = "";
        IGB igb = new IGB(FRM.ConnectString);
        bool _isNew = true;
        string _VoucherID;
        bool _isDuplicate = false;

        public frm0188()
        {
            InitializeComponent();
        }
        public frm0188(bool isNew = true, bool isView = false, string VoucherID = "", bool isDuplicate=false)
        {
            InitializeComponent();
            _isNew = isNew;
            _isDuplicate = isDuplicate;
            btnSave.Visible = !isView;
            txtVoucherNo.Enabled = isNew;
            TDBCboVoucherTypeID.Enabled = isNew;
            btnNext.Visible = isNew;
            GridDB1.PrimaryGrid.ReadOnly = isView;
            _VoucherID = VoucherID;
        }

        private void frm0222_Load(object sender, EventArgs e)
        {
            //loadDATA_Combo();            
        }

        void loadDATA_Combo()
        {
            GUI.ChangeDateFormat(dtpVoucherDate, FRM.SystemDateFormat);

            if (_isNew)
            {
                dtpVoucherDate.Value = FRM.DateDue;
            }            

            // loại chứng từ
            sql = " Select VoucherTypeID ,VoucherTypeName,WareHouseID ,VDescription , BDescription ,TDescription ,ObjectID, CreditAccountID ,isnull(IsTDescription,0) as IsTDescription ";
            sql += string.Format(" From tb0027 Where Disabled  = 0 and VoucherGroupID in ('31' ,'99') AND CHARINDEX('{0}',GroupShow)>0 Order by VoucherTypeID", FRM.ID_Group);
            TDBCboVoucherTypeID.DataSource = FRM.dt_GET(ref FRM.dt_VoucherType, sql);

            // nhân viên
            sql = string.Format("Select tb0040.ID,tb0040.EmployeeID, tb0040.FullName From tb0040 LEFT JOIN tb0071 ON tb0040.EmployeeID = tb0071.UserID LEFT JOIN tb0070 ON tb0070.GroupID = tb0071.GroupID Where tb0040.Disabled =0 and DivisionID = '{0}' and CHARINDEX('@'+CAST(tb0070.ID AS VARCHAR(20)),'{1}') > 0 Order by EmployeeID", FRM.DivisionID, FRM.ID_GroupList);
            TDBCboEmployeeID.DataSource = FRM.GetDataTable(sql);

            // loại hàng
            sql = "Select '%' as InventoryTypeID, N'<Tất cả>' as InventoryTypeName Union Select InventoryTypeID, InventoryTypeName From tb0053 Where Disabled=0 Order By InventoryTypeID";
            TDBCboInventoryTypeID.DataSource = FRM.GetDataTable(sql);

            // đối tượng
            TDBCboObjectID.DataSource = FRM.dt_Object;

            // kho
            sql = string.Format("Select WareHouseID, WareHouseName From tb0055 Where DivisionID = '{0}' And Disabled  = 0 And CHARINDEX('{1}',GroupShow)>0 ORDER BY WareHouseID", FRM.DivisionID, FRM.ID_Group);
            TDBCboWareHouseID.DataSource = FRM.GetDataTable(sql);

            // tài khoản            
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID not in ('G00', 'G05') Order by AccountID";
            DataTable dt_tb0025_CreditAccount = FRM.GetDataTable(sql);

            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID In ('G00', 'G05') Order by AccountID";
            DataTable dt_tb0025_DebitAccountID = FRM.GetDataTable(sql);
            
            SCBX.GridMultiComboBox DebitAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clDebitAccountID"].EditControl;
            DebitAccountID.ColumnWidth = new string[] { "90", "200"};
            DebitAccountID.SourceDataHeader = new string[] { "Mã TK Nợ", "Tên TK Nợ" };
            DebitAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            DebitAccountID.StringFilter = "AccountID LIKE '{0}%'";
            DebitAccountID.DisplayColumnNo = 0;
            DebitAccountID.DataSource = dt_tb0025_DebitAccountID;

            SCBX.GridMultiComboBox CreditAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clCreditAccountID"].EditControl;
            CreditAccountID.ColumnWidth = new string[] { "90", "200" };
            CreditAccountID.SourceDataHeader = new string[] { "Mã TK Có", "Tên TK Có" };
            CreditAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            CreditAccountID.StringFilter = "AccountID LIKE '{0}%'";
            CreditAccountID.DisplayColumnNo = 0;
            CreditAccountID.DataSource = dt_tb0025_CreditAccount;
            
            // khoản mục [Mã phân tích]
            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A01' Order by AnaID";
            SCBX.GridMultiComboBox clAna01ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna01ID"].EditControl;
            clAna01ID.ColumnWidth = new string[] { "100", "150", "150"};
            clAna01ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna01ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes"};
            clAna01ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna01ID.DisplayColumnNo = 0;
            clAna01ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A02' Order by AnaID";
            SCBX.GridMultiComboBox clAna02ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna02ID"].EditControl;
            clAna02ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna02ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna02ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna02ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna02ID.DisplayColumnNo = 0;
            clAna02ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A03' Order by AnaID";
            SCBX.GridMultiComboBox clAna03ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna03ID"].EditControl;
            clAna03ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna03ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna03ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna03ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna03ID.DisplayColumnNo = 0;
            clAna03ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A04' Order by AnaID";
            SCBX.GridMultiComboBox clAna04ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna04ID"].EditControl;
            clAna04ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna04ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna04ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna04ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna04ID.DisplayColumnNo = 0;
            clAna04ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A05' Order by AnaID";
            SCBX.GridMultiComboBox clAna05ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna05ID"].EditControl;
            clAna05ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna05ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna05ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna05ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna05ID.DisplayColumnNo = 0;
            clAna05ID.DataSource = FRM.GetDataTable(sql);

            // mặt hàng
            SCBX.GridMultiComboBox clInventoryID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clInventoryID"].EditControl;
            clInventoryID.ColumnWidth = new string[] { "80", "170", "100", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" };
            clInventoryID.SourceDataHeader = new string[] { "Mã hàng", "Tên hàng", "Mã ĐV Tính" };
            clInventoryID.SourceDataString = new string[] { "InventoryID", "InventoryName", "UnitID", "AccountID", "SalesAccountID", "I01ID", "I02ID", "I03ID", "I04ID", "I05ID" };
            clInventoryID.StringFilter = "InventoryID LIKE '{0}%' OR InventoryName LIKE '%{0}%'";
            clInventoryID.DisplayColumnNo = 0;
            //clInventoryID.DataSource = FRM.dt_Inventory;

            // Đối tượng THCP
            sql = "Select PeriodID, Description From tb3014 Where IsDistribute = 0 and Disabled = 0 Order by PeriodID";
            SCBX.GridMultiComboBox clPeriodID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clPeriodID"].EditControl;
            clPeriodID.ColumnWidth = new string[] { "80", "170" };
            clPeriodID.SourceDataHeader = new string[] { "Mã đối tượng", "Tên" };
            clPeriodID.SourceDataString = new string[] { "PeriodID", "Description" };
            clPeriodID.StringFilter = "PeriodID LIKE '{0}%' OR Description LIKE '%{0}%'";
            clPeriodID.DisplayColumnNo = 0;
            clPeriodID.DataSource = FRM.GetDataTable(sql);

            // Sản phẩm
            SCBX.GridMultiComboBox clProductID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clProductID"].EditControl;
            clProductID.ColumnWidth = new string[] { "80", "170" };
            clProductID.SourceDataHeader = new string[] { "Mã SP", "Tên sản phẩm" };
            clProductID.SourceDataString = new string[] { "InventoryID", "InventoryName" };
            clProductID.StringFilter = "InventoryID LIKE '{0}%' OR InventoryName LIKE '%{0}%'";
            clProductID.DisplayColumnNo = 0;
            //clProductID.DataSource = FRM.dt_Inventory;

            TDBCboInventoryTypeID.SelectedValue = "%";
        }

        private void TDBCboObjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtObjectName.Text = TDBCboObjectID.SelectedItem != null?TDBCboObjectID.SelectedItem.ItemData[1]:"";
        }        

        private void GridDB1_EndEdit(object sender, DevComponents.DotNetBar.SuperGrid.GridEditEventArgs e)
        {
            GridDB1_ValueColumnChanged(e.GridCell.RowIndex, e.GridCell.ColumnIndex);
        }

        private void Cal_Price()
        {
            double Total = 0;
            int Orders = 1;
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 2).Value != null)
                {
                    if (GridDB1.PrimaryGrid.GetCell(i, 2).Value.ToString() == "") { continue; }
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = Orders;                    
                    GridDB1.PrimaryGrid.GetCell(i, 7).Value = (GridDB1.PrimaryGrid.GetCell(i, 4).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 4).Value.ToString())) * (GridDB1.PrimaryGrid.GetCell(i, 6).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 6).Value.ToString()));
                    //GridDB1.PrimaryGrid.GetCell(i, 7).Value = (GridDB1.PrimaryGrid.GetCell(i, 6).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 6).Value.ToString())) * txtExchangeRate.Value;
                    Total = Total + (GridDB1.PrimaryGrid.GetCell(i, 7).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 7).Value.ToString()));
                    Orders += 1;
                }
                else
                {
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = null;
                }
            }
            lblTotal.Text = string.Format("{0:#,#.00}", Total);
        }

        private void TDBCboVoucherTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0104", FRM.Month, FRM.Year, FRM.DivisionID);
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            if (_isNew) { (Application.OpenForms["frm0181"] as frm0181).CloseTab(); }
            else { Close(); }
            
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            if (!Check_Form()) { return; }
            if (!Check_Table()) { return; }
            if (_isNew)
            {
                if (DLL01.GetID("tb0104", "VoucherNo", txtVoucherNo.Text, "", FRM.ConnectString))
                {
                    if (DLL02.Confirm("Số chứng từ này đã có. Bạn có muốn tạo số chứng từ mới không?", "Xác nhận"))
                    {
                        DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0104", FRM.Month, FRM.Year, FRM.DivisionID);
                    }
                    return;
                }
            }
            Save_Table();
        }

        private bool Check_Form()
        {
            if(TDBCboVoucherTypeID.Text=="")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ");
                TDBCboVoucherTypeID.Focus();
                return false;
            }
            if (txtVoucherNo.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ");
                txtVoucherNo.Focus();
                return false;
            }
            else if (TDBCboObjectID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboObjectID.Focus();
                return false;
            }
            else if (TDBCboWareHouseID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn kho nhập");
                TDBCboWareHouseID.Focus();
                return false;
            }
            else if (TDBCboEmployeeID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn người nhập phiếu");
                TDBCboEmployeeID.Focus();
                return false;
            }
           
            //Check ngày hạch toán
            //....

            return true;
        }

        private bool Check_Table()
        {
            GridDB1.Update();
            if (GridDB1.PrimaryGrid.Rows.Count < 2)
            {
                DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                return false;
            }
            else if(GridDB1.PrimaryGrid.Rows.Count>0)
            {
                int count_valid = 0;
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 2).Value == null) { continue; }
                    if (GridDB1.PrimaryGrid.GetCell(i, 2).Value.ToString().Trim() == "") { continue; }
                    if (GridDB1.PrimaryGrid.GetCell(i, 11).Value == null)
                    {
                        DLL02.Alert("Bạn phải nhập hạn sử dụng!");
                        return false;
                    }
                    count_valid++;
                }
                if (count_valid == 0)
                {
                    GridDB1.PrimaryGrid.Rows.Clear();
                    DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                    return false;
                }
            }
            return true;
        }

        private void Delete_Record()
        {
            // xóa master
            sql = string.Format("DELETE tb0104 Where DivisionID = '{0}' AND VoucherID = '{1}'", FRM.DivisionID, _VoucherID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            // xóa detail
            sql = string.Format("DELETE tb0105 Where DivisionID = '{0}' AND VoucherID = '{1}'", FRM.DivisionID, _VoucherID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
        }

        private void Save_Table()
        {
            // Lấy [VoucherID, BatchID]
            string VoucherID = _VoucherID;

            if (_isNew)
            {
                VoucherID = DLL01.Get_VoucherID(FRM.ConnectString, "tb0104", "AR", FRM.Year, "");
            }
            else
            {
                Delete_Record();
            }

            string sql = "";

            // save master
            sql = " Insert Into tb0104(VoucherID, DivisionID, TranMonth, TranYear, ObjectID, VATObjectName, EmployeeID,";
            sql += " VoucherNo,VoucherDate,WareHouseID, VoucherTypeID,KindVoucherID, ";
            sql += " Status,TableID, RefNo01,RefNo02, Description, ";
            sql += " CreateDate, CreateUserID, LastModifyDate, LastModifyUserID) Values (";
            sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", VoucherID, FRM.DivisionID, FRM.Month, FRM.Year, TDBCboObjectID.Text, "", TDBCboEmployeeID.Text);
            sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", txtVoucherNo.Text, dtpVoucherDate.Value.Date, TDBCboWareHouseID.Text, TDBCboVoucherTypeID.Text, 1);
            sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", "0", "tb0104", txtRefNo01.Text, txtRefNo02.Text, txtVDescription.Text);
            sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}')", FRM.UserName, DBNull.Value);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);

            // save detail
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 2).Value == null) { continue; }
                if (GridDB1.PrimaryGrid.GetCell(i, 2).Value.ToString().Trim() == "") { continue; }

                string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0105", "BR", FRM.Year, "");

                sql = "Insert tb0105 (TransactionID,VoucherID,InventoryID,ActualQuantity,UnitID,UnitPrice,";
                sql += " OriginalAmount,ConvertedAmount, TranMonth, TranYear, DivisionID,Orders,";
                sql += " Ana01ID,Ana02ID, Ana03ID,Ana04ID,Ana05ID, PeriodID, ProductID, OrderID, ";
                sql += " Notes, SourceNo, LocationID, LimitDate, DebitAccountID, CreditAccountID, ConversionFactor) Values(";

                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", TransactionID, VoucherID, GridDB1.GetCellVal(i, 2), GridDB1.GetCellVal(i, 4), GridDB1.GetCellVal(i, 5), GridDB1.GetCellVal(i, 6));
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB1.GetCellVal(i, 7), GridDB1.GetCellVal(i, 7), FRM.Month, FRM.Year, FRM.DivisionID, GridDB1.GetCellVal(i, 0));
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',", GridDB1.GetCellVal(i, 12), GridDB1.GetCellVal(i, 13), GridDB1.GetCellVal(i, 14), GridDB1.GetCellVal(i, 15), GridDB1.GetCellVal(i, 16), GridDB1.GetCellVal(i, 17), GridDB1.GetCellVal(i, 19), "");
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}')", GridDB1.GetCellVal(i, 10), GridDB1.GetCellVal(i, 1), GridDB1.GetCellVal(i, 21), GridDB1.PrimaryGrid.GetCell(i,11).Value, GridDB1.GetCellVal(i, 8), GridDB1.GetCellVal(i, 9), GridDB1.GetCellVal(i, 22));
                DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);
            }

            if (_isNew || _isDuplicate)
            {
                igb.SaveNewKey();
                (Application.OpenForms["frm0181"] as frm0181).loadDATA_Grid();
            }
            DLL02.Info("Lưu dữ liệu thành công");
            btnSave.Enabled = false;
        }

        private void cmdNext_Click(object sender, EventArgs e)
        {
            
            txtVDescription.Text = "";

            frm0222_Shown(null, null);
            btnSave.Enabled = true;
            lblTotal.Text = "0.00";

            GridDB1.PrimaryGrid.Rows.Clear();

        }

        private void frm0222_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            if (!_isNew)
            {
                loadDATA_Edit();
            }
        }

        void loadDATA_Edit()
        {
            sql = string.Format("SELECT * FROM tb0104 WHERE VoucherID = '{0}'", _VoucherID);
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT == null)
            {
                DLL02.Info("Bảng dữ liệu không tồn tại hoặc mất kết nối cơ sở dữ liệu\nVui lòng thử lại");
                Close();
                return;
            }
            else if (dtT.Rows.Count == 0)
            {
                DLL02.Info("Phiếu bán hàng này không tồn tại!");
                Close();
                return;
            }
            GridDB1.PrimaryGrid.DataSource = dtT;

            TDBCboVoucherTypeID.Text = dtT.Rows[0]["VoucherTypeID"].ToString();
            txtVoucherNo.Text = dtT.Rows[0]["VoucherNo"].ToString();
            txtVDescription.Text = dtT.Rows[0]["Description"].ToString();
            DateTime dateT;
            dtpVoucherDate.Value = DateTime.TryParse(dtT.Rows[0]["VoucherDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["VoucherDate"].ToString()) : DateTime.Now;         
            TDBCboObjectID.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
            TDBCboWareHouseID.SelectedValue = dtT.Rows[0]["WareHouseID"].ToString();
            TDBCboEmployeeID.SelectedValue = dtT.Rows[0]["EmployeeID"].ToString();
            TDBCboInventoryTypeID.SelectedValue = "%";
            txtRefNo01.Text = dtT.Rows[0]["RefNo01"].ToString();
            txtRefNo02.Text = dtT.Rows[0]["RefNo02"].ToString();

            sql = string.Format("SELECT * FROM vi0019 WHERE VoucherID = '{0}'", _VoucherID);
            dtT = FRM.GetDataTable(sql);
            if(dtT.Rows.Count>0)
            {
                GridDB1.PrimaryGrid.DataSource = dtT; 
            }           
            
            if(_isDuplicate)
            {
                _isNew = true;
                TDBCboVoucherTypeID.Enabled = true;
                txtVoucherNo.Enabled = true;
                DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0104", FRM.Month, FRM.Year, FRM.DivisionID);
            }
            GridDB1.Update();
            Cal_Price();
        }

        private void GridDB1_ValueColumnChanged(int RowIndex, int ColumnIndex)
        {
            GridPanel e = GridDB1.PrimaryGrid;
            GridColumn gc = e.Columns[ColumnIndex];

            if (gc.EditControl.GetType() == typeof(SCBX.GridMultiComboBox))
            {
                GridRow gr = (GridRow)e.GridPanel.ActiveRow;
                GridMultiComboBox cl = (GridMultiComboBox)gc.EditControl;

                //if (cl.SelectedItem == null) { return; }
                if (e.Columns[ColumnIndex].Name == "clInventoryID") //e.GridCell.Value == null || 
                {
                    if(cl.SelectedItem == null)
                    {
                        gr["clInventoryName"].Value = null;
                        gr["clQuantity"].Value = 0;
                        gr["clUnitID"].Value = null;
                        gr["clUnitPrice"].Value = 0;
                        gr["clOriginalAmount"].Value = 0;
                        Cal_Price();
                        return;
                    }
                    else
                    {
                        gr["clInventoryName"].Value = cl.SelectedItem.ItemData[1];
                        gr["clQuantity"].Value = 1.0;
                        gr["clUnitID"].Value = cl.SelectedItem.ItemData[2];
                        gr["clUnitPrice"].Value = 0;
                        gr["clDebitAccountID"].Value = cl.SelectedItem.ItemData[3];
                        gr["clCreditAccountID"].Value = cl.SelectedItem.ItemData[4];
                        gr["clAna01ID"].Value = cl.SelectedItem.ItemData[5];
                        gr["clAna02ID"].Value = cl.SelectedItem.ItemData[6];
                        gr["clAna03ID"].Value = cl.SelectedItem.ItemData[7];
                        gr["clAna04ID"].Value = cl.SelectedItem.ItemData[8];
                        gr["clAna05ID"].Value = cl.SelectedItem.ItemData[9];
                    }                    
                }
                else if(e.Columns[ColumnIndex].Name == "clPeriodID")
                {
                    gr["clPeriodName"].Value = cl.SelectedItem != null ? cl.SelectedItem.ItemData[1] : "";
                }
                else if (e.Columns[ColumnIndex].Name == "clProductID")
                {
                    gr["clProductName"].Value = cl.SelectedItem != null ? cl.SelectedItem.ItemData[1] : "";
                }
            }
            Cal_Price();
        }

        private void btnVoucherTypeIDSetting_Click(object sender, EventArgs e)
        {
            if (TDBCboVoucherTypeID.Text == "") { return; }
            Form frm = new frm0041(TDBCboVoucherTypeID.Text, TDBCboVoucherTypeID);
            frm.ShowDialog();
        }

        private void TDBCboWareHouseID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtWareHouseName.Text = TDBCboWareHouseID.SelectedItem != null ? TDBCboWareHouseID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboInventoryTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInventoryTypeName.Text = TDBCboInventoryTypeID.SelectedItem != null ? TDBCboInventoryTypeID.SelectedItem.ItemData[1] : "";
            if (TDBCboInventoryTypeID.SelectedItem == null) { return; };
            //sql = "SELECT InventoryID, InventoryName, UnitID, AccountID, SalesAccountID, I01ID, I02ID, I03ID, I04ID, I05ID, GroupShow  FROM tb0054 WHERE tb0054.Disabled=0 ORDER BY tb0054.InventoryID";
            //FRM.dt_Inventory = DATA.GetDataTable(sql, FRM.ConnectString, false);
            
            DataTable dt = FRM.dt_Inventory.Clone();
            DataRow[] dr = FRM.dt_Inventory.Select(string.Format("InventoryTypeID LIKE '{0}'", TDBCboInventoryTypeID.Text));
            for (int i = 0; i < dr.Count(); i++)
                dt.ImportRow(dr[i]);
            SCBX.GridMultiComboBox clInventoryID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clInventoryID"].EditControl;
            clInventoryID.DataSource = dt;
            SCBX.GridMultiComboBox clProductID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clProductID"].EditControl;
            clProductID.DataSource = dt;
        }

        private void TDBCboEmployeeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtFullname.Text = TDBCboEmployeeID.SelectedItem != null ? TDBCboEmployeeID.SelectedItem.ItemData[1] : "";
        }
    }
}
